<template>
  <div class="article">
    <mt-header fixed :title="article.title">
      <mt-button  slot="left" icon="back" @click="$router.back()">返回</mt-button>
    </mt-header>
    <div class="content" v-html="article.article.content">
    </div>
    <p class="comments-title">评论列表</p>
    <div class="comments"  v-infinite-scroll="loadMoreComments"
         infinite-scroll-disabled="loading"
         infinite-scroll-distance="10" >
      <div class="comment-row" v-for="(comment,index) in commentList" :key="comment.cid" :data-cid="comment.cid">
        <div v-show="comment.quoteId!=quoteMap['final'+comment.cid]">
          <comment  v-if="comment.quoteId>0" :quoteMap="quoteMap" :currentId="comment.cid" :comment="getQuote(comment)" :list="comments">
          </comment>
        </div>
        <p class="collapse" v-show="comment.quoteId==quoteMap['final'+comment.cid]"  @click="showCollapse">[重复引用已隐藏]</p>
        <img class="avatar" :src="comment.userImg" >
        <div class="comment-box">
          <a class="username" :href="`http://m.acfun.cn/details?upid=${comment.userID}`"> #{{comment.count}} {{comment.userName}}</a>
          <div class="comment-info" v-html="comment.content"></div>
        </div>
      </div>
    </div>
    <div class="btns-box">
      <img class="operate-btn" @click="top" src="../assets/top.png">
      <div @click="toComments">
        <img class="operate-btn"  src="../assets/comments.png">
        <mt-badge size="small"  class="comment-count">{{totalCount}}</mt-badge>
      </div>
    </div>
  </div>
</template>

<script>
  import fetch from '../utils/fetch'
  import comment from  './comment.vue'
  const EmojiUrl = 'http://cdn.aixifan.com/acfun-H5/public'
  export default {
    components:{
      comment:comment
    },
    data () {
      return {
        article:{article:{}},
        comments:{},
        commentList:[],
        allCommentIds:[],
        pageNo:1,
        loading:false,
        pageSize:30,
        totalPage:0,
        totalCount:0,
        quoteMap:{}
      }
    },
    created(){
      this.getArticle()
      this.getComments()
    },
    methods:{
      showCollapse(e){
        const ele = e.target;
        const comments = ele.previousElementSibling;
        ele.style.display = 'none'
        comments.style.display = 'block'
      },
      getArticle(){
        fetch.get(`https://acfun.leanapp.cn/acfun/contents/${this.$route.params.id}`).then(res=>{
          this.article = res.data.data;
          var maxwidth = window.innerWidth;
          this.$nextTick(()=>{
            var eles = document.querySelectorAll('.content img');
            eles.forEach(e=>{
              e.removeAttribute('height')
              e.removeAttribute('style')
              e.style.maxWidth='95%'
              e.style.margin='0 auto'
              e.style.display='block'
              while(e.parentNode.classList['value']!='content'){
                e.parentNode.removeAttribute('style')
                e = e.parentNode;
              }
            })
          })
        }).catch(err=>{
          console.log(err)
        })
      },
      getComment(id){
        return this.comments['c'+id];
      },
      getQuote(comment){
        let res = this.getComment(comment.quoteId);
        return res;
      },
      getComments(){
        let url = `https://acfun.leanapp.cn/acfun/contents/${this.$route.params.id}/comments`
        if(this.pageNo>1){
          url += `?pageNo=${this.pageNo}`
        }
        fetch.get(url).then(res=>{
          if(typeof res.data =='string'){
            this.loading = false;
            let data = JSON.parse(res.data.replace('system.tv=',""))
            let comments = data.data.commentContentArr;
            this.totalPage = data.data.totalPage;
            this.totalCount = data.data.totalCount;
            for(let v in comments){
              let ele  = comments[v]
              ele.content = -1 === ele.content.search(/(?:\[[^\]]*?\[)|(?:\][^\[]*?\])/) ? ele.content : ele.content.replace(/\[.*?\]/g, "").replace(/\[|\]/g, ""),
                ele.content = ele.content.replace(/&amp;/g, "&").replace(/&nbsp;/g, " ").replace(/&#39;/g, "'").replace(/(&quot;|&#34;)/g, '"').replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/<br\s?\/?>/g, "").replace(/((\s|&nbsp;)*\r?\n){3,}/g, "\r\n\r\n").replace(/^((\s|&nbsp;)*\r?\n)+/g, "").replace(/((\s|&nbsp;)*\r?\n)+$/g, ""),
                window.ubb2html ? (ele.content = window.ubb2html(ele.content),
                  ele.content = ele.content.replace(/\[p\]/g, "<p>").replace(/\[\/p\]/g, "</p>")) : ele.content ,
                ele.content = ele.content.replace(/\[ac\=(\S+?)\](\S+?)\[\/ac\]/g, '<a class="ac title btn" data-aid="$1" href="/v/ac$1" target="_blank"><i class="icon icon-play-circle"></i>$2</a>').replace(/\[aa\=(\S+?)\](\S+?)\[\/aa\]/g, '<a class="aa btn" href="/a/aa$1" target="_blank" title="该链接通向AcFun合辑"><i class="icon icon-list"></i>$2</a>').replace(/\[sm\=(\S+?)\](\S+?)\[\/sm\]/g, '<a class="sm btn" href="http://www.nicovideo.jp/watch/sm$1" target="_blank" title="该链接通向ニコニコ动画"><i class="icon icon-film"></i>$2</a>').replace(/\[email\](\S+?)\[\/email\]/g, '<a class="email btn" href="mailto:$1" target="_blank" title="点击以发送邮件"><i class="icon icon-envelope"></i>$1</a>').replace(/\[wiki\=(\S+?)\](\S+?)\[\/wiki\]/g, '<a class="wiki btn" href="http://wiki.acfun.cn/index.php/$1" target="_blank" title="该链接通向AC百科"><i class="icon icon-tag"></i>$2</a>');
              var a = new Date;
              3 == a.getMonth() && 1 == a.getDate() ? ele.content = ele.content.replace(/\[emot\=(\S+?)\,(\S+?)\/\]/g, '<img class="emotion flipy" style="max-width: 60px;max-height: 60px" src="' + EmojiUrl + '/umeditor/dialogs/emotion/images/$1/$2.gif">') : ele.content = ele.content.replace(/\[emot\=(\S+?)\,(\S+?)\/\]/g, '<img class="emotion" style="max-width: 60px;max-height: 60px" src="http://cdn.aixifan.com/dotnet/20130418/umeditor/dialogs/emotion/images/$1/$2.gif">'),
                ele.content = ele.content.replace(/\[acimg\](\S+?)\[\/acimg\]/g, '<img src="$1"/>').replace(/\[acimg\=(\S+?)\](\S+?)\[\/acimg\]/g, '<img src="$2"/>'),
                ele.content = ele.content.replace(/\[img\](\S+?)\[\/img\]/g, '<a class="thumb" href="$1" target="_blank" title="点击以浏览图像"><img class="preview" src="$1"></a>'),
                ele.content = ele.content.replace(/\[at\]([\s\S]+?)\[\/at\]/g, '<a class="name" target="_blank" href="http://www.acfun.cn/member/findUser.aspx?userName=$1">@$1</a>').replace(/\[\/?back.*?\]/g, "").replace(/\[username\]([\s\S]+?)\[\/username\]/g, '<a  class="name" target="_blank" href="/member/findUser.aspx?userName=$1">$1</a>').replace(/\[.*?\]/g, "").replace(/([\s\W\_])[o|O][n|N]\w+?\s*?\=/g, "$1data-event="),
                ele.content = ele.content.trim(),
                ele.content = ele.content.replace(/&amp;/g, "&").replace(/&#91;/g, "[").replace(/&#93;/g, "]")
              this.comments[v] = ele;
            }
            const commentList = [];
            data.data.commentList.forEach((v,index)=>{
              let obj = this.getComment(v);
              this.allCommentIds.push(obj.cid)
              let com = obj;
              for(let ind=1024;ind>0 && com && com.quoteId>0 && this.getComment(com.quoteId);ind--){
                if(this.allCommentIds.indexOf(com.quoteId)>=0){
                  this.quoteMap['final'+obj.cid]=com.quoteId
                  break;
                }
                this.allCommentIds.push(com.quoteId)
                com = this.getComment(com.quoteId)
              }
              commentList.push(obj);
            });
            commentList.forEach(v=>{
              this.commentList.push(v);
            })
          }
        }).catch(err=>{
          console.log(err)
        })
      },
      loadMoreComments(){
        if(this.pageNo<this.totalPage){
          this.pageNo++
          this.loading = true;
          this.getComments()
        }
      },
      toComments(){
        const dest = document.querySelector('.comments-title').offsetTop;
        window.scroll({
          behavior: 'smooth',
          left: 0,
          top: dest-200
        });
      },
      top(){
        window.scroll({
          behavior: 'smooth',
          left: 0,
          top: 0
        });
      }

    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .title,.comments-title{
    font-size: 1.1em;
    font-weight: bold;
  }
  .comment-count{
    position: absolute;
    bottom: 10px;right: 10px;
  }
  .btns-box{
    position: fixed;
    bottom: 20px;
    right: 20px;
    padding: 10px;
    background: transparent;
  }
  .operate-btn{
    width: 30px;
    height: 30px;
    display: block;
  }
  .comments-title{
    text-align: left;
  }
  .collapse{
    text-align: center;
    padding: 5px 0;
    border: thin solid #ccc;
    margin: 0;
  }
  .username{
    color: #888;
    padding: 6px;
  }
  .avatar {
    background-color: #eee;
    width: 45px;
    height: 45px;
    border-radius: 5px;
    margin-top: 5px;
    vertical-align: top;
  }
  .comment-box{
    display: inline-block;
    width: calc(100% - 60px);
  }
  .content,.comments{
    text-align: left;
  }
  .content{
    padding:40px 8px 8px;
  }
  .comment-row{
    border: 1px solid #ccc;
    padding: 2px 3px 5px;
    margin:8px;
    font-size: 12px;
  }
  .comment-info{
    padding: 6px;
    color: #666;
    word-break: break-all;
  }
  .comment-row:not(:first-child){
    margin-top: 5px;
  }
</style>
